package com.yin.myproject.zk.selector;

import org.apache.curator.framework.CuratorFramework;
import org.apache.curator.framework.recipes.leader.LeaderSelector;
import org.apache.curator.framework.recipes.leader.LeaderSelectorListenerAdapter;
import org.apache.zookeeper.WatchedEvent;
import org.apache.zookeeper.Watcher;

import java.io.Closeable;
import java.io.IOException;
import java.util.concurrent.TimeUnit;

/**
 * Created by Eason on 2017/8/7.
 */
public class MasterSelectorExample extends LeaderSelectorListenerAdapter implements Watcher, Closeable {

    private final String name;
    private final LeaderSelector leaderSelector;

    public MasterSelectorExample(CuratorFramework client, String path, String name) {
        this.name = name;
        leaderSelector = new LeaderSelector(client, path, this);
        leaderSelector.autoRequeue();
    }

    public void start() throws IOException {
        leaderSelector.start();
    }

    @Override
    public void close() throws IOException {
        leaderSelector.close();
    }

    @Override
    public void takeLeadership(CuratorFramework client) throws Exception {
        System.out.println("this is Master Node:name-->" + name);
        //为何死循环:你可以在takeLeadership进行任务的分配等等，并且不要返回，如果你想要要此实例一直是leader的话可以加一个死循环
        System.out.println("查询所有任务");
        System.out.println("在/task/node节点下拿到所有子节点,即集群服务。然后查询所有任务,将任务写入到节点中");
        while (true) {
            TimeUnit.SECONDS.sleep(60);
            Thread.currentThread().interrupt();
        }
    }

    @Override
    public void process(WatchedEvent event) {
        System.out.println("Watcher process() method:name-->" + name);
        String path = event.getPath();
        Event.EventType type = event.getType();
        System.out.println(path);
    }
}
